import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig } from "axios";
import { loadingOpen, loadingClose } from "@/componets/ClientLoading";

//客户端组件发送请求配置
interface axiosConfig extends AxiosRequestConfig {
  showLoading?: boolean;
}

const baseURL: string = "http://10.2.19.130:3050";

export function axiosInstanceClient(config?: axiosConfig): AxiosInstance {
  const instance = axios.create({
    baseURL: baseURL,
    timeout: 10000, // 超时配置
    withCredentials: false, // 跨域携带cookie
    ...config, // 自定义配置覆盖基本配置
  });

  const showLoading =
    config?.showLoading === undefined ? true : config?.showLoading;

  // 添加请求拦截器
  instance.interceptors.request.use(
    (config: any) => {
      if (showLoading) loadingOpen();
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  // 添加响应拦截器
  instance.interceptors.response.use(
    //由于客户端组件和服务端组件对于请求返回不同，所有的请求都会被当做response返回，故而不触发error。需要根据code类型进行处理
    (response: any) => {
      if (showLoading) loadingClose();
      const { code, data, message } = response.data;
      if (code === 200 && data.length !== 0) {
        return Promise.resolve({ code: 200, data: data, message: message });
      } else if (code === 200 && data.length === 0) {
        return Promise.resolve({ code: 200, message: message });
      } else if (code !== 200) {
        //此处使用reject，直接将请求状态码错误使用catch去处理，对请求返回的code码进行处理
        return Promise.reject({code:code,message:message});
      } else {
        if (
          response.headers["content-type"] ===
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          response.headers["content-type"] === "application/octet-stream"
        ) {
          return Promise.resolve(response.data);
        } else return data;
      }
    },
    (error) => {
      if (showLoading) loadingClose();
      //这是一个全局的错误处理，用来处理请求异常的情况
      return Promise.reject(error);
    }
  );
  return instance;
}
